<?php
namespace app\wechat\model;

use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Promise;

set_time_limit(0);

class HTTPModel
{
    protected $hostname = "http://localhost:9999/index.php";
    protected $client;

    private static $instances = [];
	
	// 实例化guzzle client对象
    public function __construct()
    {
        $this->client = new Client([
            'base_uri' => "{$this->hostname}",
            'timeout'  => 0,
        ]);
    }
		
    //普通请求    
    public function wechatHttp($url, $param = [], $method = 'GET'){

        try {
            $response = $this->client->request($method, $this->hostname . $url, $param);
            if($response->getStatusCode() == 200){
                $body = $response->getBody();
                $remainingBytes = $body->getContents();
                return $remainingBytes;
            }else{
                return false ;
            }
        } catch (Exception $e) {
            return false;
        }   
        
        
    }    
        
    //并发请求 
    public function poolHttp($url, $list, &$result){
        $requests = function ($url, $list) {
            foreach($list as $v){
                yield new Request('GET', $this->hostname . $url . '?' . $v);
            }
        };

        $pool = new Pool($this->client, $requests($url, $list), [
            'concurrency' => 10,
            'fulfilled' => function ($response, $index)use(&$result){
                $body = $response->getBody();
                $remainingBytes = $body->getContents();
                $result($remainingBytes, $index);
            },
            'rejected' => function ($reason, $index) {
                //print_r($reason);
                // this is delivered each failed request
            },
        ]);

        // Initiate the transfers and create a promise
        $promise = $pool->promise();

        // Force the pool of requests to complete.
        $promise->wait();
    }
	
}